package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.task;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.AbstractEntityEventHandler;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.TaskCompletedPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.exception.EventCallSuspendException;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.common.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.common.api.delegate.event.FlowableEventType;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Handler - 任务已完成事件处理器
 *
 * @author lilh
 * @date 2019-01-28 16:45
 */
@Slf4j
@Component
public class TaskCompletedHandler extends AbstractEntityEventHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private List<TaskCompletedPostProcessor> processors = new ArrayList<>();

    @Override
    public FlowableEventType getEventType() {
        return FlowableEngineEventType.TASK_COMPLETED;
    }

    @Override
    protected void doHandle(FlowableEntityEventImpl event) throws EventCallSuspendException {
        TaskEntity taskEntity = (TaskEntity) event.getEntity();
        for (TaskCompletedPostProcessor processor : processors) {
            try {
                long startTime = System.currentTimeMillis();
                processor.process(taskEntity);
                log.info("finish TASK_COMPLETED processor = {}, timeCost = {}",processor.getClass().getSimpleName(),System.currentTimeMillis()-startTime);
            } catch (EventCallSuspendException e) {
                logger.warn(e.getMessage());
                throw e;
            } catch (Exception e) {
                logger.warn("任务结束时，执行自定义逻辑发生异常：{}", ExceptionUtil.stacktraceToString(e));
                logger.error("[{}]执行出错", processor.getDesc());
            }
        }
    }


}
